package com.easy.carpanel.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.easy.carpanel.R;
import com.easy.carpanel.service.MessageEvent;
import com.easy.carpanel.uart.uartJni;
import com.easy.carpanel.until.CarUtil;
import com.easy.carpanel.view.ClockView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    byte[] write_buf1 = new byte[] {0x5a, (byte) 0xa5, 0x08, (byte)0x83, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, (byte) 0xff};
    //常量值
    float   incartemp = 0 ;    //室内温度
    float   leftclockvalue =140;   //左仪表值
    float   midclockvalue =0;    //中间仪表值
    float   rightclockvalue =0;  //右仪表值
    int  pmvalue = 0;    //  pm 的值

    @BindView(R.id.asl_num)
    TextView aslNum;     //海拔
    @BindView(R.id.temp_in)
    TextView tempIn;    //室内温度
    @BindView(R.id.temp_out)
    TextView tempOut;    //室外温度
    @BindView(R.id.clock_speed)
    ClockView clockSpeed;    //左边仪表
    @BindView(R.id.clock_mileage)
    ClockView clockMileage;    //中间仪表
    @BindView(R.id.clock_pressure)
    ClockView clockPressure;    //右边仪表
    @BindView(R.id.txt_time)
    TextView txtTime;         //时间小时分
    @BindView(R.id.txt_date)
    TextView txtDate;         //时间天
    @BindView(R.id.img_weather)
    ImageView imgWeather;      //天气图片
    @BindView(R.id.txt_pm)
    TextView txtPm;       //pm 控件
    @BindView(R.id.txt_week)
    TextView txtweek;    // 星期几

    Timer timer;           //时间触发
    TimerTask task;       //    时间定时任务

    //声明AMapLocationClient类对象    地图定位类
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象   地图定位配置类
    public AMapLocationClientOption mLocationOption = null;

    private   boolean  isFristWeather =  true;
    private   String   areacode;     //高德定位获取的城市码用来获取天气

    private Runnable readerRunnable;
    byte[] read_buf = new byte[1024];
    Handler handler = new Handler();
    int fd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
       //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象   地图定位配置
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);

        txtweek.setText(getWeek());    //设置星期几

        clockSpeed.setPercent((float)(leftclockvalue / 260.0 * 100.0));      //260为仪表盘上的值
        clockMileage.setPercent((float)(midclockvalue / 260.0 * 100.0));     //260为仪表盘上的值
        clockPressure.setPercent((float)(rightclockvalue / 260.0 * 100.0));  //260为仪表盘上的值
        tempIn.setText(incartemp+"℃");
        txtPm.setText(pmvalue+"μg/m");

        final RxPermissions rxPermissions = new RxPermissions(this);
        //请求获取定位权限
        rxPermissions
                .request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    //给定位客户端对象设置定位参数
                    mLocationClient.setLocationOption(mLocationOption);
                     //启动定位
                    mLocationClient.startLocation();

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(MainActivity.this, "GPS定位权限没有打开，请打开！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    //点击事件，这边点击天气跳转到第二个页面
    @OnClick(R.id.img_weather)
    public void onViewClicked() {
        Intent intent= new Intent(MainActivity.this,Car2Activity.class);
        startActivity(intent);
    }


    @Override
    protected void onResume() {
        String device = "/dev/ttyS4";
        fd = uartJni.open(device, 115200);
        Log.d("jiangyunwei", "open the device of " + device + ", fd is: " + fd);

        readerRunnable = new Runnable() {
            @Override
            public void run() {
                int read_count = uartJni.read(fd, read_buf, read_buf.length);

                if (read_count < 0) {
                    read_count = 0;
                }
                String  value =  CarUtil.toHex(read_buf, read_count);
                Log.d("jiangyunwei",value);
                System.out.println(value);
                List<String> list = CarUtil.getStrList(value,2);
                if(list==null || list.size()<=8){
                    handler.postDelayed(this, 1000);
                    return;
                }

                leftclockvalue =  (float) Long.parseLong(list.get(0),  16);
                midclockvalue =  (float) Long.parseLong(list.get(0),  16);
                rightclockvalue =  (float) Long.parseLong(list.get(0),  16);
                clockSpeed.setPercent((float)(leftclockvalue / 260.0 * 100.0));      //260为仪表盘上的值
                clockMileage.setPercent((float)(midclockvalue / 260.0 * 100.0));     //260为仪表盘上的值
                clockPressure.setPercent((float)(rightclockvalue / 260.0 * 100.0));  //260为仪表盘上的值

                handler.postDelayed(this, 1000);
                //相当于定时器，每隔1s执行一次该线程
            }
        };
        handler.post(readerRunnable);

        super.onResume();
    }

    @Override
    protected void onPause() {
        uartJni.close(fd);
        handler.removeCallbacks(readerRunnable);
        super.onPause();
    }

    //消息接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        if (event.message.equals("one")) {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd E");
            txtTime.setText(timeFormat.format(date));
            txtDate.setText(dateFormat.format(date));

        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);  //注册广播
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                EventBus.getDefault().post(new MessageEvent("one"));   //发送消息
            }
        };
        timer.schedule(task, 0, 1000);      //1000毫秒执行一次
    }

    @Override
    public void onStop() {
        super.onStop();
        if (timer != null) {
            timer.cancel();
            if (task != null) {
                task.cancel();
            }
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            aslNum.setText(aMapLocation.getAltitude()+"米");

            //请求高德的天气api  获取天气相关的信息
            if(isFristWeather){
            isFristWeather = false;
            OkHttpClient client = new OkHttpClient();
            areacode = aMapLocation.getAdCode();
            String  url = "https://restapi.amap.com/v3/weather/weatherInfo?"+"key=0ccb4f953a8b57bab10919ec97c18b2a&city="+areacode;
            Request request = new Request.Builder().get()
                    .url(url)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //一般会得到Json数据，这时候就要用Json解析的一系列方法处理了，网上都可查这里不多讲
                    String jsonString = response.body().string();
                    //把访问url得到的数据打印出来
                    JSONObject   json  =    JSONObject.parseObject(jsonString);
                    JSONArray   livejson =  json.getJSONArray ("lives");
                    if(livejson==null){
                       return;
                    }
                    String       weather =    livejson.getJSONObject(0).getString("weather");
                    String       temperature =    livejson.getJSONObject(0).getString("temperature");
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tempOut.setText(temperature+"℃");
                        }
                    });
                    if(weather.contains("晴")){
                       MainActivity.this.runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               imgWeather.setImageResource(R.mipmap.qing);
                           }
                       });
                    }
                    if(weather.contains("多云")){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgWeather.setImageResource(R.mipmap.duoyun);
                            }
                        });

                    }
                    if(weather.contains("阴")){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgWeather.setImageResource(R.mipmap.yin);
                            }
                        });
                    }
                    if(weather.equals("雨夹雪")){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgWeather.setImageResource(R.mipmap.yujiaxue);
                            }
                        });
                    }else if(weather.contains("雷")){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgWeather.setImageResource(R.mipmap.leiyu);
                            }
                        });
                    }else if(weather.contains("雪")){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgWeather.setImageResource(R.mipmap.xue);
                            }
                        });
                    }
                }
            });
          }
        }
    };



    public  String getWeek() {
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }

}